<template>
  <section class='f-upload-order'>
    <section class="f-title">
      <van-tabs v-model:active="searchForm.queryType" style="flex:1" color="#ffffff" background="#3273f4"
        title-active-color="#ffffff" title-inactive-color="#D8D8D8" @click-tab="clickTab">
        <van-tab title="在途订单" :name="1"></van-tab>
        <van-tab title="历史订单" :name="2"></van-tab>
      </van-tabs>

      <!-- <p v-if="searchForm.distributId" class="f-order-id" @click="openSearch">{{searchForm.distributId}}</p>
      <img v-else class="f-img1" src="@/assets/icons/jhh_icon_search_white.png" alt="" @click="openSearch"> -->
    </section>

    <ul class="f-search">
      <li class="g-flex-ct" style="width:180px" @click="openDatePicker">
        <p class="f-mr-05">{{currentDateStr}}</p>
        <van-icon name="arrow-down" />
      </li>
      <li v-if="searchForm.queryType == 2" class="g-flex-ct" @click="showStatus = true">
        <p class="f-mr-05">{{statusForm[searchForm.state ] || '全部状态'}}</p>
        <van-icon name="arrow-down" />
      </li>
      <li class="g-flex-ct" @click="showPicker = true">
        <p class="f-mr-05">{{searchForm.shopName? searchForm.shopName: '全部分销商'}}</p>
        <van-icon name="arrow-down" />
      </li>
    </ul>

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" :style="{ height: currentHeight }" style="overflow-y: auto;">
      <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <section class="f-cell-ground" v-for="(item,index) in tableData" :key="index" @click="toDetail(item)">
          <div class="f-flex-between f-cell-title">
            <p>订单编号：{{item.orderId || '--'}}</p>
            <p>{{ getDateTime(item.updatedTime)[6] }}</p>
          </div>
          <div class="f-cell f-pb-10">
            <section class="g-flex-ct">
              <img class="f-img2" src="@/assets/imgs/jhh_icon_datum.png" alt="">
              <div class="f-cell-text">
                <p>
                  <span>关联商品：</span>
                  <span>{{item.goodsName || '--'}}</span>
                </p>
                <p>
                  <span>订单来源：</span>
                  <span>{{item.shopName  || '--'}}</span>
                </p>
                <p>
                  <span>激活号码：</span>
                  <span>{{item.phone ||'--'}}</span>
                </p>
              </div>
            </section>
            <p :style="{'color': statusColor[item.state]}">
              {{statusForm[item.state]}}
            </p>
          </div>
          <p class="f-divider" v-if="index+1 < tableData.length"></p>
        </section>
      </van-list>
    </van-pull-refresh>

    <Date-Picker ref="datePickerRef" @selectDate="selectDate"></Date-Picker>

    <van-popup v-model:show="showPicker" closeable position="bottom" close-icon-position="top-left">
      <p class="f-popup-title">选择分销商</p>
      <van-picker ref="pickerRef" v-model="selectShopId" :columns="myConsumerList" :columns-field-names="customFieldName"
        :show-toolbar="false" />

      <div class="f-popup-btn">
        <van-button block type="primary" @click="handlePicker(1)">确定</van-button>
      </div>
    </van-popup>

    <van-popup v-model:show="showStatus" closeable position="bottom" close-icon-position="top-left">
      <p class="f-popup-title">状态选择</p>
      <ul class="f-status-tag">
        <li :class="{'f-status-active-btn': !searchForm.state}" @click="selectStatus(0)">全部状态</li>
        <li v-if="searchForm.queryType == 1" :class="{'f-status-active-btn': searchForm.state  == '1'}" @click="selectStatus(1)">
          待审核</li>
        <li :class="{'f-status-active-btn': searchForm.state  == '2'}" @click="selectStatus(2)">审核失败</li>
        <li :class="{'f-status-active-btn': searchForm.state  == '3'}" @click="selectStatus(3)">审核成功</li>
        <li v-if="searchForm.queryType == 1" :class="{'f-status-active-btn': searchForm.state  == '4'}" @click="selectStatus(4)">
          待上级审核</li>
        <li v-if="searchForm.queryType == 1" :class="{'f-status-active-btn': searchForm.state  == '5'}" @click="selectStatus(5)">
          上级审核成功（待分佣）</li>
        <li v-if="searchForm.queryType == 1" :class="{'f-status-active-btn': searchForm.state  == '6'}" @click="selectStatus(6)">
          资料上传成功</li>
        <li v-if="searchForm.queryType == 1" :class="{'f-status-active-btn': searchForm.state  == '7'}" @click="selectStatus(7)">
          已转发</li>
        <li v-if="searchForm.queryType == 1" :class="{'f-status-active-btn': searchForm.state  == '8'}" @click="selectStatus(8)">
          分佣成功</li>
        <li v-if="searchForm.queryType == 1" :class="{'f-status-active-btn': searchForm.state  == '9'}" @click="selectStatus(9)">
          佣金核减</li>
      </ul>
    </van-popup>
  </section>
</template>
<script>
import { ref, reactive, toRefs, onMounted, watch, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex';
import { initDatepicker, getDateTime, getUnixTime } from '@/utils/utils';
import DatePicker from '@/components/DatePicker.vue'
import api from '../api'

export default {
  components: { DatePicker },

  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const datePickerRef = ref(null)
    const pickerRef = ref()

    const state = reactive({
      searchForm: {
        "endTime": "",
        "month": "",
        "orderBy": "",
        "page": 1,
        "queryType": 1, //  1:在途订单 2:历史订单
        "size": 10,
        "startTime": "",
        "state": "",
        "distributId": ""
      },

      loading: false,
      finished: false,
      refreshing: false,
      tableData: [],
      total: 0,
      currentHeight: '500px',

      currentDateStr: "",

      showStatus: false,

      showPicker: false,
      selectShopId: [],
      myConsumerList: [],
      customFieldName: {
        text: 'shopName',
        value: 'shopId',
        children: 'children'
      },

      statusForm: {
        '1': '待审核',
        '2': '失败',
        '3': '成功',
        '4': '等待上级审核',
        '5': '待分佣',
      },
      statusColor: {
        '1': '#FF740E',
        '2': '#FF2A2A',
        '3': '#4BBC1F',
        '4': '#FF740E',
        '5': '#FF740E',
      },

      orderId: computed(() => {
        return store.state.orderId;
      }),
    })

    watch(() => state.orderId, (newVal, oldVal) => {
      state.searchForm.distributId = state.orderId
      state.refreshing = true
      onRefresh()
    })

    onMounted(() => {
      store.commit("setNavBar", {
        title: '资料审核订单',
        show: true,
        left: true,
        leftType: 'back',
        right: false,
        rightText: '去上传',
        path: '/index/uploadData'
      });

      state.currentHeight = window.innerHeight - 176 + 'px'

      let currentDateStr = getDateTime(initDatepicker(3))[3]
      state.currentDateStr = currentDateStr
      state.searchForm.month = currentDateStr

      if (route.query.tabType) {
        state.searchForm.queryType = Number(route.query.tabType)
      }

      getMyConsumerList()
    })

    const getMyConsumerList = () => {
      api.myConsumerList().then(res => {
        state.myConsumerList = res.data
        state.myConsumerList.unshift({
          shopName: '全部分销商',
          shopId: '',
        })
      })
    }

    const onLoad = () => {
      let json = JSON.parse(JSON.stringify(state.searchForm))

      if (state.refreshing) {
        state.tableData = [];
        state.refreshing = false;
      }

      api.orderInspectSearch(json).then(res => {
        state.refreshing = false

        if (res.data.records.length) state.searchForm.page += 1
        state.tableData.push(...res.data.records)

        // 防止触发两次
        if (state.tableData.length >= res.data.total) {
          state.finished = true;
        } else {
          state.finished = false;
        }

        // 加载状态结束
        state.loading = false;

        // 数据全部加载完成
        if (state.tableData.length < 10) {
          state.finished = true;
        }
      }).catch(err => {
        state.loading = false;
        state.finished = true;
        state.refreshing = false
      })
    };

    const onRefresh = () => {
      state.searchForm.page = 1

      // 清空列表数据
      state.finished = false;

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      state.loading = true;
      onLoad();
    };

    const toDetail = (params) => {
      // 记录当前tab的状态
      router.replace({
        path: '/index/auditOrder',
        query: {
          tabType: state.searchForm.queryType
        }
      })
      setTimeout(() => {
        router.push({
          path: '/index/auditDetail',
          query: {
            orderId: params.orderId
          }
        })
      }, 100)
    }

    const openDatePicker = () => {
      datePickerRef.value.datePopup = true
    }

    const selectDate = (e) => {
      if (e.popupTabs == 1) {
        let str = e.startStr + ' 至 ' + e.endStr
        state.currentDateStr = str
        state.searchForm.startTime = getUnixTime(e.startStr)
        state.searchForm.endTime = getUnixTime(e.endStr) - 999 + 24 * 60 * 60 * 1000;
        state.searchForm.month = ""
      } else {
        state.currentDateStr = e.currentDateStr
        state.searchForm.month = e.currentDateStr
        state.searchForm.startTime = ""
        state.searchForm.endTime = ""
      }
      state.refreshing = true
      onRefresh()
    }

    const selectStatus = (e) => {
      state.searchForm.state = e ? e : ''
      state.showStatus = false
      state.refreshing = true
      onRefresh()
    }

    const handlePicker = (e) => {
      let data = pickerRef.value.confirm().selectedOptions[0]
      state.showPicker = false
      state.refreshing = true
      state.searchForm.distributId = data.shopId
      state.searchForm.shopName = data.shopName
      onRefresh()
    }

    const clickTab = (e) => {
      if (e.name == 1) {
        state.searchForm.queryType = 1
        state.searchForm.state = ""
      } else {
        state.searchForm.queryType = 2
      }
      state.refreshing = true
      onRefresh()
    }

    const openSearch = () => {
      store.commit('setShowPopup', true)
    }

    return {
      ...toRefs(state),
      datePickerRef,
      pickerRef,
      onLoad,
      onRefresh,
      toDetail,
      openDatePicker,
      selectDate,
      selectStatus,
      handlePicker,
      clickTab,
      getDateTime,
      openSearch
    }
  }
}
</script>
<style lang='scss' scoped>
.f-upload-order {
  .f-title {
    background: #3273f4;
    display: flex;
    align-items: center;
    padding-bottom: 8px;
  }
  .f-order-id {
    color: #fff;
    width: 128px;
    margin-right: 20px;
    text-align: right;
  }
  .f-img1 {
    width: 18px;
    height: 19px;
    margin-left: 110px;
    margin-right: 20px;
  }
  .f-img2 {
    width: 40px;
    height: 40px;
    margin-right: 13px;
  }
  .f-search {
    font-size: 12px;
    color: #000000;
    padding: 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #f3f3f3;
  }
  .f-cell-ground {
    width: 375px;
    background: #ffffff;
    padding-left: 19px;
    .f-cell-title {
      font-size: 10px;
      color: #666666;
      padding: 10px 0;
      padding-right: 14px;
    }
    .f-cell {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-right: 14px;
      font-size: 12px;
      .f-cell-text {
        font-size: 10px;
        color: #666666;
        p {
          margin: 5px 0;
        }
        p > span:first-child {
          display: inline-block;
          width: 60px;
          text-align: right;
        }
        p > span:last-child {
          color: #000000;
        }
      }
    }
    .f-divider {
      width: 100%;
      height: 1px;
      background: #aaaaaa;
    }
  }

  .f-status-tag {
    display: flex;
    flex-wrap: wrap;
    padding-bottom: 150px;
    li {
      background: #f3f3f3;
      border: 1px solid #a9a9a9;
      border-radius: 3px;
      padding: 7px 20px;
      font-size: 13px;
      margin: 10px;
    }
  }
  .f-status-active-btn {
    background: #3273f3 !important;
    border: 1px solid #3273f3 !important;
    color: #fff;
  }
}
</style>